pipeline {

    agent any
    parameters {
        gitParameter name: 'BRANCH_NAME',
                     description: '请选择要构建的分支',

                     type: 'PT_BRANCH',

                     branchFilter: 'origin/(.*)',

                     defaultValue: 'main'

        choice(name: 'ENVIRONMENT', choices: ['dev', 'test', 'prod'], description: '选择部署环境')

        string(name: 'TAG_NAME', defaultValue: 'snapshot', description: '标签名称 必须以 v 开头.例如: v1,v1.0.0')

    }





    environment {

        DOCKER_CREDENTIAL_ID='harbor-user-pass'

        GIT_REPO_URL='192.168.2.111:30022'

        GIT_CREDENTIAL_ID='487cd21a-794e-4d7a-ab62-2a0603ba124c'

        GIT_ACCOUNT='root'

        KUBECONFIG_CREDENTIAL_ID='d30fcf0e-632c-4e4d-9798-b117e4839b77'

        REGISTRY='192.168.2.111'

        DOCKERHUB_NAMESPACE='wolfcode'

        APP_NAME='k8s-cicd-demo'

        SONAR_SERVER_URL='http://192.168.2.111:31750'

        SONAR_CREDENTIAL_ID='sonarqube-token'

    }





    stages {

        stage('Checkout') {

            steps {

                checkout([

                    $class: 'GitSCM',

                    branches: [[name: "${params.BRANCH_NAME}"]],

                    userRemoteConfigs: [[url: "http://${GIT_ACCOUNT}@${GIT_REPO_URL}/${GIT_ACCOUNT}/k8s-cicd-demo.git"]]

                ])

            }

        }

        stage('unit test') {

            steps {

                sh 'mvn clean test'

            }

        }





        stage("sonarqube analysis") {

            steps {

                withCredentials([string(credentialsId: "$SONAR_CREDENTIAL_ID", variable: "SONAR_TOKEN")]) {

                    withSonarQubeEnv('sonarqube') {

                        sh 'mvn sonar:sonar -Dsonar.projectKey=$APP_NAME'

                    }

                }

                timeout(time: 1, unit: 'HOURS') {

                    script {

                        def qg = waitForQualityGate()

                        if (qg.status!= 'OK') {

                            error "Pipeline aborted due to quality gate failure: ${qg.status}"

                        }

                    }

                }

            }

        }





        stage('build & push') {

            steps {

                sh 'mvn clean package -DskipTests'

                sh "docker build -f Dockerfile -t $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:SNAPSHOT-$BUILD_NUMBER ."

                withCredentials([usernamePassword(credentialsId: "$DOCKER_CREDENTIAL_ID", passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {

                    sh """

                        echo "$DOCKER_PASSWORD" | docker login $REGISTRY -u "$DOCKER_USERNAME" --password-stdin

                        docker push $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:SNAPSHOT-$BUILD_NUMBER

                    """

                }

            }

        }





        stage('push latest') {

            when {

                branch 'master'

            }

            steps {

                sh """

                    docker tag $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:SNAPSHOT-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:latest

                    docker push $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:latest

                """

            }

        }





        stage('deploy to dev') {

            when {

                branch 'master'

            }

            steps {

                input(id: 'deploy-to-dev', message: 'deploy to dev?')

                sh """

                    sed -i 's|REGISTRY|$REGISTRY|g' deploy/cicd-demo-dev.yaml

                    sed -i 's|DOCKERHUB_NAMESPACE|$DOCKERHUB_NAMESPACE|g' deploy/cicd-demo-dev.yaml

                    sed -i 's|APP_NAME|$APP_NAME|g' deploy/cicd-demo-dev.yaml

                    sed -i 's|BUILD_NUMBER|$BUILD_NUMBER|g' deploy/cicd-demo-dev.yaml

                    kubectl apply -f deploy/cicd-demo-dev.yaml

                """

            }

        }





        stage('push with tag') {

            when {

                expression {

                    return params.TAG_NAME =~ /^v.*/

                }

            }

            steps {

                input(id: 'release-image-with-tag', message: 'release image with tag?')

                withCredentials([usernamePassword(credentialsId: "$GIT_CREDENTIAL_ID", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {

                    sh """

                        git config --global user.email "dengyuhang@ventuo.cn"

                        git config --global user.name "dengyuhang"

                        git tag -a $TAG_NAME -m "$TAG_NAME"

                        git push http://$GIT_USERNAME:$GIT_PASSWORD@$GIT_REPO_URL/$GIT_ACCOUNT/k8s-cicd-demo.git --tags --ipv4

                    """

                }

                sh """

                    docker tag $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:SNAPSHOT-$BUILD_NUMBER $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:$TAG_NAME

                    docker push $REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:$TAG_NAME

                """

            }

        }





        stage('deploy to production') {

            when {

                expression {

                    return params.TAG_NAME =~ /^v.*/

                }

            }

            steps {

                input(id: 'deploy-to-production', message: 'deploy to production?')

                sh """

                    sed -i 's|REGISTRY|$REGISTRY|g' deploy/cicd-demo.yaml

                    sed -i 's|DOCKERHUB_NAMESPACE|$DOCKERHUB_NAMESPACE|g' deploy/cicd-demo.yaml

                    sed -i 's|APP_NAME|$APP_NAME|g' deploy/cicd-demo.yaml

                    sed -i 's|TAG_NAME|$TAG_NAME|g' deploy/cicd-demo.yaml

                    kubectl apply -f deploy/cicd-demo.yaml

                """

            }

        }

    }

}